

import time
from fastapi.responses import JSONResponse
from utils.asr import only_asr
from video2audio import download_video, fenli, main, video2audio
from fastapi import FastAPI
# from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
from typing import Optional
from logger import v_logger


class TTSERS(BaseModel):
    url: Optional[str] = None
    type: Optional[str] = None


app = FastAPI()
# 添加CORS中间件
# app.mount("/static", StaticFiles(directory="static"), name="static")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# 音视频文字提取


@app.post("/ast_audio")
async def asAdudiotPost(json: TTSERS):
    t0 = time.time()
    url = json.url
    local_name = download_video(url, 'tmp', "mp3")
    if local_name is None:
        v_logger.info(f"下载视频报错")
        return None
    _, merged_segments = only_asr(url)
    # Calculate execution time
    end_time = time.time()
    execution_time = end_time - t0
    minutes = int(execution_time // 60)
    seconds = int(execution_time % 60)
    print(f"执行时间: {minutes}分{seconds}秒")
    if merged_segments is None:
        merged_segments = []

    return JSONResponse(status_code=200, content={"msg": "", "code": 0, "data": merged_segments})


@app.post("/ast_video")
async def astPost(json: TTSERS):
    url = json.url
    type = json.type
    v_logger.info("url: {}, type: {}".format(url, type))
    result = main(url, type)
    v_logger.info(result)
    if result is None:
        result = ""

    return result


# 音视频分离
@app.post("/fenli_video")
async def fenliPost(json: TTSERS):
    url = json.url
    type = json.type
    v_logger.info("url: {}, type: {}".format(url, type))
    result = fenli(url, type)
    v_logger.info(result)
    if result is None:
        result = ""

    return result


if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0',
                port=8080, workers=1)
